import { initGlobalState, MicroAppStateActions } from 'qiankun';

// 初始化 state
const initialState = {
    token: localStorage.getItem('token'),
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    isLogin: !!localStorage.getItem('token')
};

// 创建全局状态实例
const actions = initGlobalState(initialState);

// 定义一个变量来保存最新的状态
let globalState: any = initialState;

// 监听全局状态变更
actions.onGlobalStateChange((state, prev) => {
    // 更新本地存储的状态
    globalState = state;
    console.log('主应用观察到全局状态变更：', state, prev);
    
    // 更新本地存储
    if (state.token !== prev.token) {
        localStorage.setItem('token', state.token || '');
    }
    if (state.userInfo !== prev.userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(state.userInfo || {}));
    }
});

// 扩展 actions，添加获取状态的方法
const enhancedActions = {
    ...actions,
    // 获取当前全局状态
    getGlobalState: () => globalState
};

export default enhancedActions; 